<?php
namespace app\index\controller;

use app\common\model\AttachMain;
use app\index\controller\Base;
use think\facade\Request;

class Upload extends Base
{

    public function index()
    {
        return json([
            'expire'      => (int) request()->time() + 30,
            'host'        => url('index/upload/local_attach'),
            'delete_host' => '',
        ]);
    }

    public function local_attach()
    {
        global $_G;
        if (empty($_G['uid'])) {
            return show_error('请先登录后在操作');
        }
        $file = Request::file('file');
        if (empty($file)) {
            return show_error('请选择文件');
        }
        $savename = \think\facade\Filesystem::putFile('attach', $file);
        $savename = str_replace(DIRECTORY_SEPARATOR, '/', $savename);
        if (!is_file($savename)) {
            return show_error('文件上传失败');
        }
        $attach = AttachMain::create([
            'uid'         => $_G['uid'],
            'from'        => 'upload',
            'filename'    => $file->getOriginalName(),
            'filesize'    => filesize($savename),
            'savename'    => $savename,
            'queue_error' => '',
            'button_name' => '立即下载',
            'local_file'  => $savename,
            'status'      => 2,
        ]);
        return show_success('', '', ['savename' => $attach->savename, 'attach_id' => $attach->attach_id]);
    }
}
